package net.chenlin.dp.ids.client.filter;

import net.chenlin.dp.ids.client.config.PassportClientConfig;
import net.chenlin.dp.ids.client.manager.AuthCheckManager;
import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.util.JsonUtil;
import net.chenlin.dp.ids.common.util.WebUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ids app过滤器
 * @author zcl<yczclcn@163.com>
 */
public class PassportAppAuthFilter implements Filter {

    private FilterConfig filterConfig;

    private PassportClientConfig clientConfig;

    private AuthCheckManager authCheckManager;

    public PassportAppAuthFilter(PassportClientConfig clientConfig, AuthCheckManager authCheckManager) {
        this.clientConfig = clientConfig;
        this.authCheckManager = authCheckManager;
    }

    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * 过滤器链
     * @param request
     * @param response
     * @param chain
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        String servletPath = servletRequest.getServletPath();
        String accessPolicy = clientConfig.matchAccessPolicy(servletPath);
        // 匿名请求，访问策略为ANON_ACCESS
        if (IdsConst.ANON_ACCESS_POLICY.equals(accessPolicy)) {
            chain.doFilter(request, response);
            return;
        }
        SessionData sessionData = authCheckManager.checkAppSession(servletRequest);
        // 登出请求
        if (IdsConst.LOGOUT_URL.equals(servletPath)) {
            // 如果app已登录，则登出
            if (sessionData != null) {
                // 删除sessionData
                authCheckManager.removeAppSession(servletRequest);
            }
            BaseResult logoutRes = GlobalErrorEnum.SUCCESS.getResult();
            WebUtil.write(servletResponse, JsonUtil.toStr(logoutRes));
            return;
        }
        // 未登录，并且访问策略为AUTH_ACCESS
        if (sessionData == null && IdsConst.AUTH_ACCESS_POLICY.equals(accessPolicy)) {
            BaseResult notLoginRes = GlobalErrorEnum.NOT_LOGIN.getResult();
            WebUtil.write(servletResponse, JsonUtil.toStr(notLoginRes));
            return;
        }
        // 登录成功，或者访问策略为 ROUTER_ACCESS
        request.setAttribute(IdsConst.SESSION_KEY, sessionData);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

}
